package com.wy.music_player;

import com.wy.adapter.DBAdapter;
import com.wy.domain.User;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/*
	Login
 */
public class Login extends Activity{
	private final String TAG = "Login";
	// UI OBJECT
	EditText ed_username,ed_password;
	Button login,sign;
	// USER INFO
	String username ="",password="";
	private DBAdapter DBadapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_layout);

		bindViews();
		// login
		login.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				username = ed_username.getText().toString();
				password = ed_password.getText().toString();
				
				if(!username.equals("") && !password.equals("")){
					// create or open  databse
					if(DBadapter == null)
						DBadapter = new DBAdapter(Login.this);
					DBadapter.open();
					boolean flag = DBadapter.login(username, password);
					if(flag){
						Toast.makeText(Login.this, "login successful ,welcome " + username, Toast.LENGTH_SHORT);
						User user = DBadapter.getUserByUsernameAndPassword(username,password);
						Log.i("Login", "login.onClick: user = " + user.toString());
						Intent it = new Intent(Login.this,MainActivity.class);
						it.putExtra("username",user.getUsername());
						it.putExtra("sex",user.getSex());
						it.putExtra("country",user.getCountry());
						it.putExtra("id",user.getID());
						startActivity(it);
						finish();
					}
					else{
						Toast.makeText(Login.this, "login error:Account or password error", Toast.LENGTH_SHORT);
						return;
					}
				}else{
					Toast.makeText(Login.this, "Account or password cannot be empty", Toast.LENGTH_SHORT);
				}
			}
		});
		
		// sign
		sign.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent it = new Intent(Login.this,Sign.class);
				startActivityForResult(it,1);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 1 && resultCode == 2){
			ed_username.setText(data.getStringExtra("username"));
			ed_password.setText(data.getStringExtra("password"));
		}
	}

	private void bindViews(){
		ed_username = (EditText) findViewById(R.id.username);
		ed_password = (EditText) findViewById(R.id.password);
		login = (Button) findViewById(R.id.login);
		sign = (Button) findViewById(R.id.sign);
	}
}
